//
//  BabyPhotoListVIew.m
//  BabyHelper
//
//  Created by  thomas on 11-8-14.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "BabyPhotoListView.h"


@implementation BabyPhotoListView
@synthesize babyPhotos;
@synthesize whereClause,photoCategory;
@synthesize viewMode;
#pragma mark -
#pragma mark View lifecycle


- (void)viewDidLoad {
    [super viewDidLoad];

	self.babyPhotos = [[NSMutableArray alloc]init];
	
	switch (self.viewMode) {
		case EditMode:
		{
			self.title = NSLocalizedString(@"Edit Photo", @"");
			UIBarButtonItem *deleteItem = [[UIBarButtonItem alloc]
										   initWithTitle:NSLocalizedString(@"Del",@"")
										   style:UIBarButtonItemStyleBordered 
										   target:self
										   action:@selector(toggleDelete)		
										   ];
			self.navigationItem.rightBarButtonItem = deleteItem;
			[deleteItem release];			
			break;
		}
		case ShareMode:
			self.title = NSLocalizedString(@"Share Photo", @"");
			break;
		default:
			break;
	}
		
	//self.tableView.separatorColor = [UIColor clearColor];
	
	//set background image
	self.parentViewController.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"background"]];
	self.view.backgroundColor = [UIColor clearColor];
	//set navigation background color
	self.navigationController.navigationBar.tintColor = [UIColor colorWithRed:navBarRed green:navBarGreen blue:navBarBlue alpha:navBarAlpha];
}

- (void)viewWillAppear:(BOOL)animated {
	[super viewWillAppear:animated];
	Dao *dao = [Dao getInstance];
	[self.babyPhotos removeAllObjects];
	NSString *whereClause = @"WHERE categoryID = 0 and thumpath != 'null' ORDER BY TIMESTAMP DESC";
	[dao QueryBabyPhotoEntryWith:whereClause records:self.babyPhotos];
	[self.tableView reloadData];
}
#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.babyPhotos count];
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	PhotoManager *photoManager = [PhotoManager getInstance];    

	static NSString *CellIdentifier = @"BabyPhotoViewCellIdentifier";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }
    
	BabyPhotoEntry *entry = [self.babyPhotos objectAtIndex:indexPath.row];	
	
	NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
	[dateFormatter setDateFormat:DATE_TIME_FORMAT];
	cell.textLabel.text = [dateFormatter stringFromDate:entry.timestamp];
	[dateFormatter release];
	cell.detailTextLabel.text = [entry getSummaryStringWithoutTimestamp]; 
	cell.detailTextLabel.textColor = [UIColor colorWithRed:commentsTextRed green:commentsTextGreen blue:commentsTextBlue alpha:commentsTextAlpha];
	cell.backgroundColor = [UIColor colorWithRed:cellBackgroundRed green:cellBackgroundGreen 
											blue:cellBackgroundBlue alpha:cellBackgroundAlpha];
	cell.imageView.image = [photoManager GetThumPhotoByPhotoID:entry.index];
	
	switch (viewMode) {
		case EditMode:
			cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;	
			break;
		case ShareMode:
		{
			UIImage *image = [UIImage imageNamed:@"Sina_32x32"];
			UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
			CGRect frame = CGRectMake(0.0, 0.0, image.size.width, image.size.height);
			button.frame = frame;	// match the button's size with the image size
			[button setBackgroundImage:image forState:UIControlStateNormal];
			// set the button's target to this table view controller so we can interpret touch events and map that to a NSIndexSet
			[button addTarget:self action:@selector(accessoryButtonTapped:event:) forControlEvents:UIControlEventTouchUpInside];
			cell.accessoryView = button;			
			break;
		}
		default:
			break;
	}
		
    return cell;	
}


-(NSString *)GetReportContentWithIndexPath:(NSIndexPath *)indexPath{
	
	BabyPhotoEntry *entry = [self.babyPhotos objectAtIndex:indexPath.row];	
	Dao *dao = [Dao getInstance];
	BabyProfile *babyProfile = [[BabyProfile alloc]init];
	[dao LoadBabyProfile:babyProfile];

	NSString *report = [NSString stringWithFormat:BABY_PHOTO_ENTRY_CONTENT_STR,
						babyProfile.Name,
						[dao GetAgeStringWithTwoDate:babyProfile.Birthday toDateTS:[entry.timestamp timeIntervalSince1970]],
						[entry getSummaryStringWithoutTimestamp]];
	
	[babyProfile release];
	
	return report;
}

// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
		PhotoManager *photoManager = [PhotoManager getInstance];
		
        // Delete the row from the data source
		BabyPhotoEntry *entry = [self.babyPhotos objectAtIndex:[indexPath row]];
		
		//if change the pic, should delete old pic first;
		if(![entry.photoPath isEqualToString:@"null"] &&
		   ![entry.thumPath isEqualToString:@"null"])
		{
			remove([[NSString stringWithFormat:@"%@/Documents/%@",NSHomeDirectory(),entry.photoPath] cStringUsingEncoding:NSASCIIStringEncoding]);
			remove([[NSString stringWithFormat:@"%@/Documents/%@",NSHomeDirectory(),entry.thumPath] cStringUsingEncoding:NSASCIIStringEncoding]);
		}
		[photoManager RemoveThumImageByPhotoID:entry.index];
		
		Dao *dao = [Dao getInstance];
		[dao RemoveBabyPhotoEntry:entry];
		[self.babyPhotos removeObjectAtIndex:[indexPath row]];
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
    }   
}

#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	
	if (self.viewMode == EditMode) {
		EditBabyPhotoView *childView = [[EditBabyPhotoView alloc] initWithNibName:@"EditBabyPhoto" bundle:nil];
		childView.currentBabyPhotoEntry = [self.babyPhotos objectAtIndex:indexPath.row];
		[self.navigationController pushViewController:childView animated:YES];
		[childView release];
	}
}

#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Relinquish ownership any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
}

- (void)dealloc {
    [super dealloc];
	//[self.babyPhotos release];
}

-(void)toggleDelete{
	[self.tableView setEditing:!self.tableView.editing animated:YES];
	
	if (self.tableView.editing)
		[self.navigationItem.rightBarButtonItem setTitle:NSLocalizedString(@"Done",@"")];
	else
		[self.navigationItem.rightBarButtonItem setTitle:NSLocalizedString(@"Del",@"")];
}

- (void)accessoryButtonTapped:(id)sender event:(id)event
{
	NSSet *touches = [event allTouches];
	UITouch *touch = [touches anyObject];
	CGPoint currentTouchPosition = [touch locationInView:self.tableView];
	NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint: currentTouchPosition];
	if (indexPath != nil)
	{
		[self tableView: self.tableView accessoryButtonTappedForRowWithIndexPath: indexPath];
	}
}

- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath
{	
	
	BabyHelperAppDelegate *appDelegate = (BabyHelperAppDelegate *)[[UIApplication sharedApplication] delegate];
	UIViewController *controller = [OAuthController controllerToEnterCredentialsWithEngine: appDelegate._engine delegate: self];
	if (controller) 
	{
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Alert",@"") 
														message:NSLocalizedString(@"You are not log in yet", @"")
													   delegate:nil 
											  cancelButtonTitle:@"OK"
											  otherButtonTitles:nil];
		[alert show];
		[alert release];
	}
	else {
		NSLog(@"Authenicated for %@..", appDelegate._engine.username);
		[OAuthEngine setCurrentOAuthEngine:appDelegate._engine];
		[[NSUserDefaults standardUserDefaults] setValue:[self GetReportContentWithIndexPath:indexPath] forKey:@"SavedWeiBoText"];
		ComposeViewController *composeViewController = [[ComposeViewController alloc]init];
		[self presentModalViewController:composeViewController animated:YES];
		composeViewController.messageTextField.text = [self GetReportContentWithIndexPath:indexPath];
		
		[composeViewController newTweet];					
		
		BabyPhotoEntry *entry = [self.babyPhotos objectAtIndex:indexPath.row];
		
		if ( ![entry.photoPath isEqualToString:@"null"] ) {
			UIImage *image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/Documents/%@",NSHomeDirectory(),entry.photoPath]];
			[composeViewController setImage:image movie:nil];
		}
	}		
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
	return kBabyPhotoListViewRowHeight;
}

@end